今天逛CodePen的時候看到會跳的愛心感覺超可愛,就試著來練習看看吧。
來源:Blinking Heart!!
先做基本設定,放數字是比較容易看旋轉位置,之後會刪除
	<div class="heart">123</div>
$bgc: red;
.heart{
    width: 200px;
    height: 200px;
    background-color:$bgc&::before,
    &::after {
        content:'';//注意這行一定要加
        width: 200px;
        height: 200px;
        border-radius: 50%;
        background-color: $bgc;
        position: absolute;
        top: -100px;
        left: 0;
    };
}
向右旋轉45度
transform: rotate(45deg);
用偽元素製作圓角
	&::before,
    &::after {
        content:'';//注意這行一定要加
        width: 200px;
        height: 200px;
        border-radius: 50%;
        background-color: $bgc;
        position: absolute;
        top: -100px;
        left: 0;
    }
再把 ::before 和 ::after 的位置分開,把定位分開寫比較好修改
ps這時候把偽元素背景顏色改掉,可以看到正方形上有兩個圓圈
	&::before,
    &::after {
        content: ''; //注意這行一定要加
        width: 200px;
        height: 200px;
        border-radius: 50%;
        background-color: $bgc;
        position: absolute;
    }
    &::before {
        top: 0;
        left: -100px;
    }
    &::after {
        top: -100px;
        left: 0;
    }
接下來製作跳動效果
// 愛心的動畫
@keyframes heartBeat{
    0%{
        transform: scale(1) rotate(45deg);
        //旋轉角度一定要加,不然會用未旋轉的角度執行動畫
    }
    10%{
        transform: scale(1.25) rotate(45deg);//縮放1.25倍
    }
    100%{
        transform: scale(1) rotate(45deg);//回到原來大小
    }
}
然後在heart加上動畫的控制項就可以看到愛心開始跳動
.heart{
(略)
animation: heartBeat 1.5s infinite; //infinite = 重複播放
}
加上眼睛
// 右眼
.right-eye {
    z-index: 10;
    width: 15px;
    height: 15px;
    border-radius: 50%;
    background-color: $eyes;
    position: absolute;
    right: 120px;
    top: -10px;
}
//左眼
.left-eye {
    z-index: 10;
    width: 15px;
    height: 15px;
    border-radius: 50%;
    background-color: $eyes;
    position: absolute;
    left: -10px;
    bottom: 120px;
}
眨眼動畫
// 眼睛動畫
@keyframes blink {
    0%,
    100% {
        transform: scale(1, 0.5);
        //x軸不動,y軸變化
    }
    5%,
    95% {
        transform: scale(1,1);
    }
}
把控制項放入左右眼
.left-eye {
(略)
    animation: blink 1s infinite;
}
加上嘴巴會比較可愛
// 嘴巴
.mouth{
    z-index: 10;
    width: 65px;
    height: 10px;
    border-radius: 50%;
    background-color: $eyes;
    position: absolute;
    top: 50px;
    left: 25px;
    transform: rotate(135deg);
}
為了讓跳動時˙有顏色變化,在跳動到10%時加變色效果
@keyframes heartBeat {
(略)
    10% {
        transform: scale(1.25) rotate(45deg); //縮放1.25倍
        background-color: #e5383b;
    }
(略)
}
但這時會發現 ::before 和 ::after 兩個偽元素沒有跟著變色,這時就要針對這部分另外寫動畫
@keyframes heartBeatBgc {
    10% {
        background-color: #e5383b;
    }
}
把控制項放入偽元素內就完成了
.heart {
(略)
    &::before,
    &::after {
 (略)
        animation: heartBeatBgc 1.5s infinite;
    }
}
